﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Data;
using System.Collections;

namespace AdminPack.SiteColumns
{
    [ToolboxItemAttribute(false)]
    public class SiteColumns : WebPart
    {
        private bool _error = false;
        private GridView gvList;
        private DropDownList ddlGroups;

        public SiteColumns()
        {
            this.ExportMode = WebPartExportMode.All;
        }

        protected override void CreateChildControls()
        {
            if (!_error)
            {
                try
                {

                    base.CreateChildControls();

                    ddlGroups = new DropDownList();
                    ddlGroups.AutoPostBack = true;
                    Controls.Add(ddlGroups);

                    gvList = new GridView();
                    gvList.AutoGenerateColumns = false;
                    gvList.HeaderStyle.CssClass = "ms-viewheadertr ms-vb";
                    gvList.AlternatingRowStyle.CssClass = "ms-vb ms-alternating";
                    gvList.RowStyle.CssClass = "ms-vb2";
                    gvList.RowCommand += new GridViewCommandEventHandler(gvList_RowCommand);

                    HyperLinkField hyp = new HyperLinkField();
                    hyp.DataTextField = "FieldName";
                    hyp.DataNavigateUrlFields = new string[] { "InternalName" };
                    hyp.DataNavigateUrlFormatString = "/_layouts/fldedit.aspx?field={0}";
                    hyp.ItemStyle.Width = Unit.Pixel(300);
                    hyp.HeaderText = "Field Name";
                    hyp.HeaderStyle.CssClass = "ms-vh2";
                    gvList.Columns.Add(hyp);

                    BoundField fldID = new BoundField();
                    fldID.DataField = "ID";
                    fldID.HeaderText = "ID";
                    fldID.ItemStyle.Width = Unit.Pixel(300);
                    fldID.HeaderStyle.CssClass = "ms-vh2";
                    gvList.Columns.Add(fldID);

                    BoundField fldInternal = new BoundField();
                    fldInternal.DataField = "InternalName";
                    fldInternal.HeaderText = "Internal Name";
                    fldInternal.ItemStyle.Width = Unit.Pixel(300);
                    fldInternal.HeaderStyle.CssClass = "ms-vh2";
                    gvList.Columns.Add(fldInternal);

                    ButtonField fldButt = new ButtonField();
                    fldButt.CommandName = "FindContentTypes";
                    fldButt.Text = "Find";
                    fldButt.HeaderText = "Content Types";
                    fldButt.HeaderStyle.CssClass = "ms-vh2";
                    gvList.Columns.Add(fldButt);

                    Controls.Add(gvList);
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
            }
        }

        protected void gvList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "FindContentTypes")
            {
                GridViewRow gvr = gvList.Rows[Convert.ToInt32(e.CommandArgument)];
                string id = gvr.Cells[1].Text;
                string internalName = gvr.Cells[2].Text;
                string contentTypes = "";

                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    SPWeb web = site.RootWeb;

                    foreach (SPContentType ct in web.ContentTypes)
                    {
                        try
                        {
                            SPField fld = ct.Fields.GetFieldByInternalName(internalName);
                            contentTypes += ct.Name + ";";
                        }
                        catch { }
                    }
                }

                gvr.Cells[3].Text += "<br/>" + contentTypes.Replace(";", "<br/>");
            }
        }

        /// <summary>
        /// Ensures that the CreateChildControls() is called before events.
        /// Use CreateChildControls() to create your controls.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            if (!_error)
            {
                try
                {
                    base.OnLoad(e);
                    this.EnsureChildControls();

                    using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                    {
                        SPWeb web = site.RootWeb;
                        string selGroup;

                        selGroup = "All";
                        if (Page.IsPostBack)
                            selGroup = ddlGroups.SelectedValue;

                        DataSet ds = CreateListDataset();
                        string groups = "";

                        foreach (SPField fld in web.Fields)
                        {
                            if (fld.Group == selGroup || selGroup == "All")
                            {
                                DataRow ndr = ds.Tables[0].NewRow();
                                ndr["FieldName"] = fld.Title;
                                ndr["ID"] = fld.Id.ToString();
                                ndr["InternalName"] = (fld.InternalName);
                                ds.Tables[0].Rows.Add(ndr);
                                groups += fld.Group + ";";
                            }
                        }

                        if (!Page.IsPostBack)
                        {//Load group list on page load
                            string[] listGroups = groups.Split(';');
                            Array.Sort(listGroups);
                            ArrayList finalgroups = new ArrayList();
                            string cont = "";
                            foreach (string s in listGroups)
                            {
                                if (s != cont)
                                {
                                    cont = s;
                                    finalgroups.Add(new ListItem(s));
                                }
                            }

                            ddlGroups.DataSource = finalgroups;
                            ddlGroups.DataBind();

                            ddlGroups.Items.Insert(0, new ListItem("All"));
                        }

                        DataSet fds = CreateListDataset();
                        DataRow[] flds = ds.Tables[0].Select("", "FieldName");

                        foreach (DataRow dr in flds)
                            fds.Tables[0].ImportRow(dr);

                        gvList.DataSource = fds;
                        gvList.DataBind();
                    }
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
            }
        }

        public static DataSet CreateListDataset()
        {
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("FieldName", System.Type.GetType("System.String")));
            dt.Columns.Add(new DataColumn("ID", System.Type.GetType("System.String")));
            dt.Columns.Add(new DataColumn("InternalName", System.Type.GetType("System.String")));
            ds.Tables.Add(dt);
            return ds;
        }

        /// <summary>
        /// Clear all child controls and add an error message for display.
        /// </summary>
        /// <param name="ex"></param>
        private void HandleException(Exception ex)
        {
            this._error = true;
            this.Controls.Clear();
            this.Controls.Add(new LiteralControl(ex.Message));
        }
    }
}
